<!--
 @description
 @fileName NativeFile.vue
 @author zengqiongying
 @created 2022/12/08 10:13:45
-->
<template>
  <div class="c-file-input-icon">
    <img :src="camera" @click.stop="openCamera">
    <img v-if="showAlbum" :src="album" @click.stop="openAlbum">
    <!-- <img :src="folder" @click.stop="openFolder"> -->
  </div>
</template>

<script>
import folder from '@/assets/upload/folder.png'
import album from '@/assets/upload/album.png'
import camera from '@/assets/upload/camera.png'

function dataURLtoBlob(baseurl) {
  const mime = 'image/jpeg'
  const bstr = atob(baseurl)
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

export default {
  name: 'NativeSelectFile',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    needPicNum: {
      type: Number,
      default: 1
    },
    showAlbum: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      folder,
      album,
      camera
    }
  },

  computed: {
    popVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },

  created() {},
  activated() {},

  mounted() {},

  methods: {
    openCamera() {
      this.$nativeHandler('openCamera').then((res) => {
        const data = {
          target: {
            files: (res.data || []).map((e) => {
              return new File([dataURLtoBlob(e)], `${new Date().getTime()}.${res.type}`, {
                type: `image/${res.type}`
              })
            })
          }
        }
        this.$emit('success', data)
      }).catch((err) => {
        this.$emit('error', err)
      }).finally(() => {
        this.popVisible = false
      })
    },
    openAlbum() {
      const needPicNum = this.limit <= 0 ? 1 : this.limit
      this.$nativeHandler('openAlbum', { needPicNum: needPicNum }).then((res) => {
        console.log('选择的文件')
        console.log(res.data)
        const data = {
          target: {
            files: (res.data || []).map((e) => {
              return new File([dataURLtoBlob(e)], `${new Date().getTime()}.${res.type}`, {
                type: `image/${res.type}`
              })
            })
          }
        }
        this.$emit('success', data)
      }).catch((err) => {
        this.$emit('error', err)
      }).finally(() => {
        this.popVisible = false
      })
    },
    openFolder() {
      const i = this.$el.querySelector('#c-file-input')
      this.visible = false
      if (i) {
        i.click()
      }
    }
  }
}

</script>
<style lang='less' scoped>
  .c-file-input-icon {
    display: flex;
    padding: 15px 5px;
    justify-content: space-around;
    box-sizing: border-box;
    & > img {
      flex: 0 0 40px;
      width: 40px;
      height: 40px;
    }
  }
</style>
